package com.spring.campus_express_delivery.controller;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.github.pagehelper.PageInfo;
import com.spring.campus_express_delivery.entity.*;
import com.spring.campus_express_delivery.interceptor.RequiredPermission;
import com.spring.campus_express_delivery.service.ExpressTypeService;
import com.spring.campus_express_delivery.service.OrdersService;
import com.spring.campus_express_delivery.util.JwtToken;
import com.spring.campus_express_delivery.util.MyUtil;
import com.spring.campus_express_delivery.util.RedisUtil;
import com.spring.campus_express_delivery.util.ResponseEntity;
import com.sun.org.apache.xpath.internal.operations.Or;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@CrossOrigin
@Controller
@RequestMapping("/orders")
@Api(value = "OrdersController", description = "订单相关api")
public class OrdersController {
    Boolean flag;
    MyUtil myUtil = new MyUtil();
    @Autowired
    OrdersService ordersService;
    @Autowired
    ExpressTypeService expressTypeService;
    @Autowired
    RedisUtil redisUtil;

    /**
     * 添加订单（orderNum通过随机产生，order_status添加时直接赋值为未接，）
     *
     * @param remark
     * @param orderType_price
     * @param user_name
     * @param phone
     * @param pick_code
     * @param expressWeightType
     * @param expressCompanyType
     * @param serviceAddress
     * @return
     * @throws IOException
     * @throws TokenExpiredException
     * @Header Authorization
     */
    @ApiOperation("发布订单")
    @PostMapping("wx/insert_order")
    @ResponseBody
    public ResponseEntity insertOrder(@RequestParam(required = false) String remark,
                                      @RequestParam(required = false) Double orderType_price,
                                      @RequestParam(required = false) String user_name,
                                      @RequestParam(required = false) String phone,
                                      @RequestParam(required = false) String pick_code,
                                      @RequestParam(required = false) String expressWeightType,
                                      @RequestParam(required = false) String expressCompanyType,
                                      @RequestParam(required = false) String serviceAddress,
                                      @RequestHeader String Authorization) throws IOException, TokenExpiredException, ParseException, InvocationTargetException, IllegalAccessError {
        ResponseEntity responseEntity;
        String token = Authorization;
        Users users = JwtToken.unsign(token, Users.class);
        responseEntity = ResponseEntity.ok();
        Orders orders = new Orders();
        orders.setUser_identity_id(users.getIdentity_id());
        //随机产生的+当前时间作为订单编号
        orders.setOrderNum(myUtil.getRandom() + myUtil.getTime());
        orders.setRemark(remark);
        String order_status = "未接";
        orders.setOrder_status(order_status);
        orders.setOrderType_price(orderType_price);
        orders.setUser_name(user_name);
        if (myUtil.isNumLegal(phone)) {
            orders.setPhone(phone);
        } else {
            responseEntity.putDataValue("msg", "手机号码长度不是11位不合法");
        }
        orders.setOrder_time(myUtil.getTime());
        orders.setEnd_time(myUtil.getWeeksTime());
        orders.setPick_code(pick_code);
        orders.setExpressWeightType(expressWeightType);
        orders.setExpressCompanyType(expressCompanyType);
        orders.setServiceAddress(serviceAddress);
        String whether_delete = "否";
        orders.setWhether_delete(whether_delete);
        ordersService.insertOrder(orders);
        responseEntity.putDataValue("id",orders.getId());
        responseEntity.putDataValue("msg", "添加成功");
        return responseEntity;
    }

    /**
     * 接单(修改订单状态为已接同时设置接单员学号/工号）
     *
     * @param id
     * @param Authorization
     * @throws IOException
     */
    @ApiOperation("接单(修改订单状态为已接同时设置接单员学号/工号）")
    @PostMapping("/wx/update_order_status1")
    @ResponseBody
    public ResponseEntity updateOrderStatus(@RequestParam(required = true) Integer id, @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        Users users = JwtToken.unsign(token, Users.class);
        Orders orders = ordersService.selectId(id);
        if (orders == null) {
            responseEntity = ResponseEntity.notFound();
            responseEntity.putDataValue("msg", "订单不存在");
            return responseEntity;
        }
        String order_status = "已接";
        orders.setOrder_status(order_status);
        orders.setSender_id(users.getIdentity_id());
        ordersService.updateOrderStatus(orders);
        responseEntity = ResponseEntity.ok();
        responseEntity.putDataValue("id",orders.getId());
        responseEntity.putDataValue("msg", "接单成功");
        //删除缓存
        String key = "orders_" + id;
        if (redisUtil.hasKey(key)){
            redisUtil.del(key);
        }
        return responseEntity;
    }

    /**
     * 确认收货(修改订单状态为已完成）
     *
     * @param id
     * @param Authorization
     * @throws IOException
     */
    @ApiOperation("确认收货(修改订单状态为已完成）")
    @PostMapping("/wx/update_order_status2")
    @ResponseBody
    public ResponseEntity updateOrderStatusByF(@RequestParam(required = true) Integer id, @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        Users users = JwtToken.unsign(token, Users.class);
        Orders orders = ordersService.selectId(id);
        if (orders == null) {
            responseEntity = ResponseEntity.notFound();
            responseEntity.putDataValue("msg", "订单不存在");
            return responseEntity;
        }
        if (orders.getUser_identity_id().equals(users.getIdentity_id())) {
            String order_status = "已完成";
            orders.setOrder_status(order_status);
            orders.setSign_time(myUtil.getTime());
            ordersService.updateOrderStatusByF(orders);
            responseEntity = ResponseEntity.ok();
            responseEntity.putDataValue("id",orders.getId());
            responseEntity.putDataValue("msg", "确认收货成功");
            //删除缓存
            String key = "orders_" + id;
            if (redisUtil.hasKey(key)){
                redisUtil.del(key);
            }
            return responseEntity;
        } else {
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg", "该用户没有权利");
        }
        return responseEntity;
    }

    /**
     * 取消接单(根据订单编号修改订单状态为未接同时设置接单员学号/工号为空）（要是想实现接单员取消订单需要发布员同意方可取消，怎么实现？）
     *
     * @param id
     * @param Authorization
     * @throws IOException
     */
    @ApiOperation("取消订单(根据订单编号修改订单状态为未接同时设置接单员学号/工号为空）")
    @PostMapping("/wx/update_order_status3")
    @ResponseBody
    public ResponseEntity updateOrderStatusByCancel(@RequestParam(required = true) Integer id, @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        Users users = JwtToken.unsign(token, Users.class);
        Orders orders = ordersService.selectId(id);
        if (orders.getId() == null) {
            responseEntity = ResponseEntity.notFound();
            responseEntity.putDataValue("msg", "订单不存在");
        }
        if (orders.getSender_id().equals(users.getIdentity_id())) {
            String order_status = "未接";
            orders.setOrder_status(order_status);
            String sender_id = null;
            orders.setSender_id(sender_id);
            orders.setOrder_time(myUtil.getTime());
            ordersService.updateOrderStatusByCancel(orders);
            responseEntity = ResponseEntity.ok();
            responseEntity.putDataValue("id",orders.getId());
            responseEntity.putDataValue("msg", "取消接单成功");
            //删除缓存
            String key = "orders_" + id;
            if (redisUtil.hasKey(key)){
                redisUtil.del(key);
            }
            return responseEntity;
        } else {
            responseEntity = ResponseEntity.unauthorized();
            responseEntity.putDataValue("msg", "该用户没有权利");
        }
        return responseEntity;
    }

    /**
     * 修改订单
     *
     * @param id
     * @param remark
     * @param order_status
     * @param orderType_price
     * @param user_name
     * @param phone
     * @param pick_code
     * @param expressWeightType
     * @param expressCompanyType
     * @param serviceAddress
     * @param Authorization
     * @return
     */
    @ApiOperation("修改订单（只有发布员才可以修改订单）")
    @PostMapping("/wx/update_order")
    @ResponseBody
    public ResponseEntity updateOrders(@RequestParam(required = true) Integer id,
                                       @RequestParam(required = false) String remark,
                                       @RequestParam(required = false) String order_status,
                                       @RequestParam(required = false) Double orderType_price,
                                       @RequestParam(required = false) String user_name,
                                       @RequestParam(required = false) String phone,
                                       @RequestParam(required = false) String pick_code,
                                       @RequestParam(required = false) String expressWeightType,
                                       @RequestParam(required = false) String expressCompanyType,
                                       @RequestParam(required = false) String serviceAddress,
                                       @RequestHeader String Authorization) throws IOException {

        ResponseEntity responseEntity;
        String token = Authorization;
        Users users = JwtToken.unsign(token, Users.class);
        Orders orders = ordersService.selectId(id);
        if (orders.getUser_identity_id().equals(users.getIdentity_id())) {
            responseEntity = ResponseEntity.ok();
            orders.setRemark(remark);
            orders.setOrder_status(order_status);
            orders.setOrderType_price(orderType_price);
            orders.setUser_name(user_name);
            //MyUtil工具类中的isNumLegal方法采用正则表达式验证手机号码的格式
            if (myUtil.isNumLegal(phone)) {
                orders.setPhone(phone);
            } else {
                responseEntity = ResponseEntity.forbidden();
                responseEntity.putDataValue("msg", "手机号码不合法");
                return responseEntity;
            }

            orders.setOrder_time(myUtil.getTime());
            orders.setPick_code(pick_code);
            orders.setExpressWeightType(expressWeightType);
            orders.setExpressCompanyType(expressCompanyType);
            orders.setServiceAddress(serviceAddress);
            ordersService.updateOrders(orders);
//            responseEntity.putDataValue("id",orders.getId());
            responseEntity.putDataValue("msg", "订单修改成功");
            //删除缓存
            String key = "orders_" + id;
            if (redisUtil.hasKey(key)){
                redisUtil.del(key);
            }
            return responseEntity;
        } else {
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg", "没有修改订单的权限");
            return responseEntity;
        }

    }

    /**
     * 订单列表（订单管理）
     *
     * @param size
     * @param page
     * @param sort
     * @param asc
     * @param response
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("订单管理（发布员自己发布的订单列表）")
    @GetMapping("/wx/ordersSelf_list")
    @ResponseBody
    public ResponseEntity selectOrdersSelf(@RequestParam(value = "size", required = false, defaultValue = "10") int size,
                                           @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                           @RequestParam(value = "sort", required = false, defaultValue = "id") String sort,
                                           @RequestParam(value = "asc", required = false, defaultValue = "asc") String asc,
                                           @RequestHeader String Authorization,
                                           HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        /*星号表示所有的域都可以接受，*/
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");

        ResponseEntity responseEntity;
        String token = Authorization;
        Users users = JwtToken.unsign(token, Users.class);
        String identity_id = users.getIdentity_id();
        PageBean<Orders> pagemsg = ordersService.selectOrdersSelfByPage(identity_id, size, page, sort, asc);
        responseEntity = ResponseEntity.ok();
        responseEntity.putDataValue("records", pagemsg);
        return responseEntity;


    }
    /**
     * 订单列表（查询所有订单)
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("查询所有未删除的订单")
    @GetMapping("/wx/selectAllOrders")
    @ResponseBody
    public ResponseEntity selectAllOrders(@RequestParam(value = "pageNo",defaultValue = "1")Integer pageNo,
                                          @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize,
                                          @RequestHeader String Authorization) throws IOException {


        ResponseEntity responseEntity;
        String token = Authorization;
        PageInfo<Orders> orders = ordersService.selectAllOrders(pageNo,pageSize);
        responseEntity = ResponseEntity.ok();
        responseEntity.putDataValue("orders", orders);
        return responseEntity;

    }
    /**
     * 订单列表（接单页面的订单列表）
     *
     * @param size
     * @param page
     * @param sort
     * @param asc
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("接单页面订单列表")
    @GetMapping("/wx/orders_list")
    @ResponseBody
    public ResponseEntity selectOrders(@RequestParam(value = "size", required = false, defaultValue = "10") int size,
                                       @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                       @RequestParam(value = "sort", required = false, defaultValue = "id") String sort,
                                       @RequestParam(value = "asc", required = false, defaultValue = "asc") String asc,
                                       @RequestHeader String Authorization) throws IOException {

        ResponseEntity responseEntity;
        String token = Authorization;
        PageBean<Orders> pagemsg = ordersService.selectOrdersByPage(size, page, sort, asc);
        responseEntity = ResponseEntity.ok();
        responseEntity.putDataValue("records", pagemsg);
        return responseEntity;

    }

    /**
     * 订单列表（自己接单的订单列表）
     * @param size
     * @param page
     * @param sort
     * @param asc
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("个人中心的订单详情(用户接的订单列表）")
    @GetMapping("/wx/ordersBySendID_list")
    @ResponseBody
    public ResponseEntity selectBySender(@RequestParam(value = "size", required = false, defaultValue = "10") int size,
                                         @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                         @RequestParam(value = "sort", required = false, defaultValue = "id") String sort,
                                         @RequestParam(value = "asc", required = false, defaultValue = "asc") String asc,
                                         @RequestHeader String Authorization) throws IOException {


        ResponseEntity responseEntity;
        String token = Authorization;
        Users users = JwtToken.unsign(token, Users.class);
        String identity_id = users.getIdentity_id();
        PageBean<Orders> pagemsg = ordersService.selectBySender(identity_id, size, page, sort, asc);
        responseEntity = ResponseEntity.ok();
        responseEntity.putDataValue("records", pagemsg);
        return responseEntity;

    }

    /**
     * 删除订单
     * @param id
     * @return
     * @throws IOException
     */
    @ApiOperation("删除订单")
    @DeleteMapping("/wx/delete_order")
    @ResponseBody
    public ResponseEntity deleteOrder(@RequestParam(required = true) Integer id, @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        //通过token解密出来的user对象
        Users user = JwtToken.unsign(token, Users.class);
        Orders orders = ordersService.selectId(id);
        if (orders.getUser_identity_id() != null) {
            if (orders.getUser_identity_id().equals(user.getIdentity_id())) {
                ordersService.deleteOrderById(id);
                responseEntity = ResponseEntity.ok();
                responseEntity.putDataValue("id",orders.getId());
                responseEntity.putDataValue("msg", "删除数据成功");
                //删除缓存
                String key = "orders_" + id;
                if (redisUtil.hasKey(key)){
                    redisUtil.del(key);
                }
                return responseEntity;
            } else {
                responseEntity = ResponseEntity.forbidden();
                responseEntity.putDataValue("msg", "没有删除订单的权限");
                return responseEntity;
            }
        } else {
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg", "发布订单的用户不存在，无法删除订单");
            return responseEntity;
        }


    }

    /**
     * 查询订单详情
     * @param id
     * @return
     * @throws IOException
     */
    @ApiOperation("查询订单详情")
    @GetMapping("/wx/select_orderById")
    @ResponseBody
    public ResponseEntity selectOrderById(@RequestParam(required = true) Integer id, @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        //通过token解密出来的user对象
        Users user = JwtToken.unsign(token, Users.class);
        //查询缓存
        String key = "orders_" + id;
        boolean b = redisUtil.hasKey(key);
        //如果redis中存在 查询缓存
        if (b){
            Orders orders = (Orders) redisUtil.get(key);
            responseEntity=ResponseEntity.ok();
            responseEntity.putDataValue("Orders",orders);
            return responseEntity;
        }
        responseEntity = ResponseEntity.ok();
        Orders orders = ordersService.selectId(id);
        responseEntity.putDataValue("Orders", orders);
        //设置缓存
        redisUtil.set("orders_" + id, orders);
        return responseEntity;
    }
    /**
     * 根据类型查询订单列表
     * @param size
     * @param page
     * @param sort
     * @param asc
     * @param type
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("根据类型查询订单列表")
    @GetMapping("/web/selectType")
    @ResponseBody
    public ResponseEntity selectType(@RequestParam(value = "size", required = false, defaultValue = "10") int size,
                                                    @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                                    @RequestParam(value = "sort", required = false, defaultValue = "id") String sort,
                                                    @RequestParam(value = "asc", required = false, defaultValue = "asc") String asc,
                                                    @RequestParam String type,
                                                    @RequestHeader String Authorization) throws IOException {

        ResponseEntity responseEntity;
        String token = Authorization;
        //通过token解密出来的user对象
        Users user = JwtToken.unsign(token, Users.class);
        PageBean<Orders> pagemsg = ordersService.selectOrderByExpressWeightTypeByPage(size, page, sort, asc, type);
        responseEntity = ResponseEntity.ok();
        responseEntity.putDataValue("records", pagemsg);
        return responseEntity;


    }

    /**
     * 根据快递重量类型查询订单列表
     * @param size
     * @param page
     * @param sort
     * @param asc
     * @param expressWeightType
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("根据快递重量类型查询订单列表")
    @GetMapping("/web/expressWeightType_list")
    @ResponseBody
    public ResponseEntity selectByExpressWeightType(@RequestParam(value = "size", required = false, defaultValue = "10") int size,
                                                    @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                                    @RequestParam(value = "sort", required = false, defaultValue = "id") String sort,
                                                    @RequestParam(value = "asc", required = false, defaultValue = "asc") String asc,
                                                    @RequestParam String expressWeightType,
                                                    @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        //通过token解密出来的user对象
        Users user = JwtToken.unsign(token, Users.class);
        PageBean<Orders> pagemsg = ordersService.selectOrderByExpressWeightTypeByPage(size, page, sort, asc, expressWeightType);
        responseEntity = ResponseEntity.ok();
        responseEntity.putDataValue("records", pagemsg);
        return responseEntity;

    }

    /**
     * 根据快递公司类型查询订单列表
     * @param size
     * @param page
     * @param sort
     * @param asc
     * @param expressCompanyType
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("根据快递公司类型查询订单列表")
    @GetMapping("/web/expressCompanyType_list")
    @ResponseBody
    public ResponseEntity selectByExpressCompanyType(@RequestParam(value = "size", required = false, defaultValue = "10") int size,
                                                     @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                                     @RequestParam(value = "sort", required = false, defaultValue = "id") String sort,
                                                     @RequestParam(value = "asc", required = false, defaultValue = "asc") String asc,
                                                     @RequestParam String expressCompanyType,
                                                     @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;

        //通过token解密出来的user对象
        Users user = JwtToken.unsign(token, Users.class);
        PageBean<Orders> pagemsg = ordersService.selectOrderByExpressCompanyTypeByPage(size, page, sort, asc, expressCompanyType);
        responseEntity = ResponseEntity.ok();
        responseEntity.putDataValue("records", pagemsg);
        return responseEntity;
    }

    /**
     * 根据送达地址查询订单列表
     * @param size
     * @param page
     * @param sort
     * @param asc
     * @param serviceAddress
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("根据送达地址查询订单列表")
    @GetMapping("/web/serviceAddress_list")
    @ResponseBody
    public ResponseEntity selectByServiceAddress(@RequestParam(value = "size", required = false, defaultValue = "10") int size,
                                                 @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                                 @RequestParam(value = "sort", required = false, defaultValue = "id") String sort,
                                                 @RequestParam(value = "asc", required = false, defaultValue = "asc") String asc,
                                                 @RequestParam String serviceAddress,
                                                 @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        //通过token解密出来的user对象
        Users user = JwtToken.unsign(token, Users.class);
        PageBean<Orders> pagemsg = ordersService.selectOrderByServiceAddressByPage(size, page, sort, asc, serviceAddress);
        responseEntity = ResponseEntity.ok();
        responseEntity.putDataValue("records", pagemsg);
        return responseEntity;
    }

    /**
     * 根据订单状态查询订单列表
     * @param size
     * @param page
     * @param sort
     * @param asc
     * @param order_status
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("根据订单状态查询订单列表（自己发布的订单列表）")
    @GetMapping("/web/selectByOrderStatus_list")
    @ResponseBody
    public ResponseEntity selectByOrderStatus(@RequestParam(value = "size", required = false, defaultValue = "10") int size,
                                              @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                              @RequestParam(value = "sort", required = false, defaultValue = "id") String sort,
                                              @RequestParam(value = "asc", required = false, defaultValue = "asc") String asc,
                                              @RequestParam String order_status,
                                              @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        //通过token解密出来的user对象
        Users user = JwtToken.unsign(token, Users.class);
        String identity_id=user.getIdentity_id();
        PageBean<Orders> pagemsg = ordersService.selectOrderByOrderStatusByPage(size, page, sort, asc, order_status,identity_id);
        responseEntity = ResponseEntity.ok();
        responseEntity.putDataValue("records", pagemsg);
        return responseEntity;
    }

    /**
     * 修改快递进度接口
     * @param id
     * @param pictureFile
     * @param Authorization
     * @throws IOException
     */
    @ApiOperation("修改快递进度")
    @PostMapping("/wx/update_middle_address")
    @ResponseBody
    public ResponseEntity updateMiddle_address(HttpServletRequest request, Integer id, @RequestParam MultipartFile pictureFile, @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        Users users = JwtToken.unsign(token, Users.class);
        String middle_address = MyUtil.testPrint(pictureFile);
        Orders orders = ordersService.selectId(id);
        if (users.getIdentity_id().equals(orders.getSender_id())) {
            orders.setMiddle_address(middle_address);
            ordersService.updateMiddle_address(orders);
            responseEntity = ResponseEntity.ok();
            responseEntity.putDataValue("id",orders.getId());
            responseEntity.putDataValue("msg", "快递进度修改成功");
            //删除缓存
            String key = "orders_" + id;
            if (redisUtil.hasKey(key)){
                redisUtil.del(key);
            }
            return responseEntity;
        } else {
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg", "该用户没有权限");
            return responseEntity;
        }

    }

    /**
     * 查看快递进度接口
     * @param id
     * @param Authorization
     * @throws IOException
     */
    @ApiOperation("查看快递进度接口")
    @GetMapping("/wx/select_middle_address")
    @ResponseBody
    public ResponseEntity selectMiddle_address(@RequestParam(required = true) Integer id, @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        Users users = JwtToken.unsign(token, Users.class);
        //查询缓存
        String key = "orders_" + id;
        boolean b = redisUtil.hasKey(key);
        //如果redis中存在 查询缓存
        if (b){
            Orders orders = (Orders) redisUtil.get(key);
            if (users.getIdentity_id().equals(orders.getUser_identity_id())||users.getIdentity_id().equals(orders.getSender_id())) {
                responseEntity = ResponseEntity.ok();
                responseEntity.putDataValue("id",orders.getId());
                responseEntity.putDataValue("msg", orders.getMiddle_address());
                return responseEntity;
            } else {
                responseEntity = ResponseEntity.forbidden();
                responseEntity.putDataValue("msg", "该用户没有权限");
                return responseEntity;
            }
        }
        Orders orders = ordersService.selectId(id);
        if (users.getIdentity_id().equals(orders.getUser_identity_id())||users.getIdentity_id().equals(orders.getSender_id())) {
            responseEntity = ResponseEntity.ok();
            responseEntity.putDataValue("id",orders.getId());
            responseEntity.putDataValue("msg", orders.getMiddle_address());
            //设置缓存
            redisUtil.set("orders_" + id, orders);
            return responseEntity;
        } else {
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg", "该用户没有权限");
            return responseEntity;
        }

    }

    /**
     * 统计订单数量
     */
    @ApiOperation("统计订单数量")
    @GetMapping("/wx/count_order")
    @ResponseBody
    public ResponseEntity Orders_count() throws IOException {
        ResponseEntity responseEntity;
        Map<String, Integer> count = ordersService.Orders_count();
        responseEntity = ResponseEntity.ok();
        responseEntity.putDataValue("count", count);
        return responseEntity;
    }

//    /**
//     * 导入订单信息
//     *
//     * @param orderFiles
//     * @Header Authorization
//     * @throws IOException
//     */
//    @ApiOperation("导入订单信息api")
//    @PostMapping("web/importOrdersExcel")
//    @ResponseBody
//    @RequiredPermission(1)
//    public ResponseEntity importOrdersExcel(MultipartFile orderFiles,@RequestHeader String Authorization) throws IOException {
//        String token = Authorization;
//        ordersService.importOrdersExcel(orderFiles);
//        ResponseEntity responseEntity;
//        responseEntity = ResponseEntity.ok();
//        responseEntity.putDataValue("msg", "订单信息导入成功");
//        return responseEntity;
//    }

    /**
     * poi将数据库中的用户数据批量导出到Excel
     * @param response
     * @Header Authorization
     * @throws Exception
     */
    @ApiOperation("导出订单信息api")
    @PostMapping("web/exportOrdersExcel")
    @ResponseBody
    @RequiredPermission(1)
    public void exportOrdersExcel(HttpServletResponse response,@RequestHeader String Authorization) throws Exception {
        ordersService.exportOrdersExcel(response);
    }

    /**
     * 根据取件码、用户名、联系方式、备注模糊查询订单
     * @param keyWord
     * @throws IOException
     */
    @ApiOperation("根据取件码、用户名、联系方式、备注模糊查询订单（自己发布的订单页面查询）")
    @GetMapping("wx/selectOrderByPick_code")
    @ResponseBody
    public ResponseEntity selectOrderByPick_code(@RequestParam String keyWord, @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        Users users = JwtToken.unsign(token, Users.class);
        List<Orders> orders = ordersService.selectOrderByPick_code(keyWord);
        HashMap<String,Object> map = new HashMap<String,Object>();

        for(int i=0;i<orders.size();i++) {
            if (users.getIdentity_id().equals(orders.get(i).getUser_identity_id()) ) {

                 map.put("orders"+i,orders.get(i));
            }

        }
        responseEntity = ResponseEntity.ok();
        responseEntity.putDataValue("map", map);
        return responseEntity;

    }
    /**
     * 根据取件码、用户名、联系方式、备注模糊查询订单
     * @param keyWord
     * @throws IOException
     */
    @ApiOperation("根据取件码、用户名、联系方式、备注模糊查询订单(web端查询订单)")
    @GetMapping("web/selectOrderByKeyWord")
    @ResponseBody
    public ResponseEntity selectOrderByKeyWord(@RequestParam String keyWord, @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        Users users = JwtToken.unsign(token, Users.class);
        List<Orders> orders = ordersService.selectOrderByPick_code(keyWord);

        responseEntity = ResponseEntity.ok();
        responseEntity.putDataValue("orders", orders);
        return responseEntity;

    }

}
